package com.bigmi.admin.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigmi.admin.mapper.AdminLoginMapper;
import com.bigmi.admin.service.AdminLoginService;
import com.bigmi.model.admin.dto.AdUserDto;
import com.bigmi.model.admin.pojo.AdUser;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.AppHttpCodeEnum;
import com.bigmi.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdUser> implements AdminLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //判断是否为空
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询用户
        LambdaQueryWrapper<AdUser> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(queryWrapper);
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //密码比对
        String salt = adUser.getSalt();
        String password = dto.getPassword();
        password= DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if (password.equals(adUser.getPassword())){
            Map<String,Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("adUser",adUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }


    }
}
